<?php

/**
 * account actions.
 *
 * @package    vmdai
 * @subpackage account
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class accountActions extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
      public function executeIndex(sfWebRequest $request){

        $this->getResponse()->setTitle("我的账户");
          $user_id = $this->getUser()->getAttribute("user_id");
          $this->user_account = Doctrine::getTable('UserAccount')->findOneByUserId($user_id);
          $loaning = Doctrine::getTable("LoanRecord")->createQuery()->select("count(id) as count,sum(loan_money) as loan_money")->where("status = ?",0)->andWhere("user_id = ?",$user_id)->fetchOne();
                    $sql = "SELECT SUM(current_principal_money) as current_principal_money,
                            SUM(current_interest_money) as current_interest_money FROM `invest_installment` WHERE user_id = $user_id AND status = 0
                    AND loan_id NOT IN (SELECT `loan_id` FROM `invest_installment` WHERE `status` = 4)";
          $wait_result = Doctrine_Manager::connection()->execute("$sql")->fetch();
          
          //总本金，总利息
          $sql = "SELECT SUM(current_principal_money) as current_principal_money,
                            SUM(current_interest_money) as current_interest_money FROM `invest_installment` WHERE user_id = $user_id AND status <> 2";
         
          $sum_result = Doctrine_Manager::connection()->execute("$sql")->fetch();

          $sql = "SELECT current_end_time,SUM(current_money) as current_money
                   FROM `loan_installment` WHERE loan_user_id = $user_id AND status = 0
                   AND loan_id NOT IN (SELECT `loan_id` FROM `loan_installment` WHERE `status` = 4)";
         $wait_pay = Doctrine_Manager::connection()->execute("$sql")->fetch();
        $today = date("Y-m-d H:i:s");
        $end_day = date("Y-m-d H:i:s",time()+2592000);
        $sql = "SELECT SUM(current_money) as current_money
        FROM `loan_installment` WHERE loan_user_id = $user_id AND status = 0 AND current_end_time Between '$today' AND '$end_day'
        AND loan_id NOT IN (SELECT `loan_id` FROM `loan_installment` WHERE `status` = 4)";
        $wait_lasted_pay = Doctrine_Manager::connection()->execute("$sql")->fetch();
        
        //回款中
        $sql = "SELECT SUM(current_money) as current_money
                FROM `invest_installment` WHERE user_id = $user_id AND status = 0 AND current_end_time ".
                 "AND loan_id NOT IN (SELECT `loan_id` FROM `invest_installment` WHERE `status` = 4) group by loan_id";
       
        $repayment = Doctrine_Manager::connection()->execute("$sql")->fetchAll();
        $repaymenting["count"]=count($repayment);
        $repaymenting["current_money"]=0;
        foreach($repayment as $k){
           $repaymenting["current_money"]+=$k['current_money'];
        }
         //已回款
        $sql = "SELECT SUM(current_money) as current_money FROM `invest_installment` WHERE user_id = $user_id AND loan_id IN (SELECT `id` FROM `loan` WHERE `status` = 5) group by loan_id";
       
        $already = Doctrine_Manager::connection()->execute("$sql")->fetchAll();
        $already_repaymenting["count"]=count($already);
        $already_repaymenting["current_money"]=0;
        foreach($already as $k){
           $already_repaymenting["current_money"]+=$k['current_money'];
        }
        
        $start_month = date("Y-m")."-01"." 00::00:00";
        $days = date('t');
        $end_month = date("Y-m")."-"."$days 00::00:00";
         $sql = "SELECT COUNT(id) as count,SUM(current_money) as current_money
                FROM `invest_installment` WHERE user_id = $user_id AND status = 0 AND current_end_time Between '$start_month' AND '$end_month'
                    AND loan_id NOT IN (SELECT `loan_id` FROM `invest_installment` WHERE `status` = 4)";
        // echo $sql;exit;
        $td_month_repaymenting = Doctrine_Manager::connection()->execute("$sql")->fetch();

        
        //下月待回款
        $next_start_month = date('Y-m',strtotime('+1 month'))."-01 00::00:00";
        $next_days = date('t',strtotime('+1 month'));
        $next_end_month = date("Y-m",strtotime('+1 month'))."-"."$next_days 00::00:00";
        $sql = "SELECT COUNT(id) as count,SUM(current_money) as current_money
                FROM `invest_installment` WHERE user_id = $user_id AND status = 0 AND current_end_time Between '$next_start_month' AND '$next_end_month'
                    AND loan_id NOT IN (SELECT `loan_id` FROM `invest_installment` WHERE `status` = 4)";
        $next_month_repaymenting = Doctrine_Manager::connection()->execute("$sql")->fetch();
        //本年待回款
        $td_start_year = date("Y")."-01-01 00:00:00";
        $td_end_year = date("Y")."-12-31 00:00:00";
        $sql = "SELECT COUNT(id) as count,SUM(current_money) as current_money
                FROM `invest_installment` WHERE user_id = $user_id AND status = 0 AND current_end_time Between '$td_start_year' AND '$td_end_year'
                    AND loan_id NOT IN (SELECT `loan_id` FROM `invest_installment` WHERE `status` = 4)";
        $td_year_repaymenting = Doctrine_Manager::connection()->execute("$sql")->fetch();

        $this->user_result =  array(
            'loaning'=>$loaning,
            'repaymenting'=>$repaymenting,
            'wait_result'=>$wait_result,
            'sum_result'=>$sum_result,
            'wait_pay'=>$wait_pay,
            'wait_lasted_pay'=>$wait_lasted_pay,
            'already_repaymenting'=>$already_repaymenting,
            'td_month_repaymenting'=>$td_month_repaymenting,
            'next_month_repaymenting'=>$next_month_repaymenting,
            'td_year_repaymenting'=>$td_year_repaymenting
        );
                                             
         //判断用户是否验证过身份证
          $this->user_auth = Doctrine::getTable('UserAuth')->findOneByUserId($user_id);
      }
      

      //账户交易细节
      public function executeDetails(sfWebRequest $request) {
        $this->getResponse()->setTitle("交易明细");
        $user_id = $this->getUser()->getAttribute('user_id',0);
        $this->forward404Unless($this->user_account = Doctrine::getTable('UserAccount')->findOneByUserId($user_id));
        $this->startDate = "";
        $this->endDate = "";
        if($request->isMethod("POST")){
          $this->startDate = $request->getParameter("startDate");
          $this->endDate = $request->getParameter("endDate");
        }
        
        $this->cash_money = Doctrine::getTable('UserAccountCashRecord')->createQuery()->select('sum(next_money) as money')->where('user_id = ?',$user_id)->andWhere('status = ?',1)->fetchOne()->toArray();
       
        if(!empty($this->startDate) && !empty($this->endDate)){
           $sql = Doctrine::getTable('AccountDetails')->createQuery()
                   ->where('user_id = ?',$this->user_account->getUserId())
                   ->andWhere("created_at >= ?",$this->startDate."00:00:00")
                   ->andWhere("created_at <= ?",$this->endDate."00:00:00")
                   ->orderBy('id desc');
           
        }else{
          $sql = Doctrine::getTable('AccountDetails')->createQuery()->where('user_id = ?',$this->user_account->getUserId())->orderBy('id desc');
        } 
        $page = $request->getParameter('page',1);
        $this->pager = new sfDoctrinePager('AccountDetails',10);
        $this->pager->setQuery($sql);
        $this->pager->setPage($page);
        $this->pager->init();
       
        
      }
      
      //11月之前账户交易细节
      public function executeDetailsold(sfWebRequest $request) {
        $this->getResponse()->setTitle("11月之前账户交易明细");
        $user_id = $this->getUser()->getAttribute('user_id',0);
       
        $this->forward404Unless($this->user_account = Doctrine::getTable('UserAccount')->findOneByUserId($user_id));
        $this->cash_money = Doctrine::getTable('UserAccountCashRecord')->createQuery()->select('sum(next_money) as money')->where('user_id = ?',$user_id)->andWhere('status = ?',1)->fetchOne()->toArray();
        $sql="select * from account_details_old where user_id= ".$this->user_account->getUserId()." order by id asc";
        $this->user_account_details = Doctrine_Manager::connection()->execute("$sql")->fetchAll();
        
        
      }
      
      
      public function executeRecharge(sfWebRequest $request){
        $this->getResponse()->setTitle("账户充值");
          $user_id = $this->getUser()->getAttribute("user_id");
           //判断用户是否已经完成认证
          $user_auth = Doctrine::getTable('UserAuth')->findOneByUserId($user_id);
          if(empty($user_auth)){
              //没有认证过
              $this->auth=0;
          }else{
              if($user_auth->getPhone() =="0" || $user_auth->getIdCard() =="0"){
                  $this->auth=0;
              }else{
                  $this->auth=1;
              }
          }
          
         //银行列表
         $this->bank_list = Doctrine::getTable('BankTypes')->createQuery()
                                                        ->where('is_display = ?',1)
                                                        ->execute();
         
         //余额
         $this->user = Doctrine::getTable('UserAccount')->findOneByUserId($user_id);
         
         if( $request->isMethod("POST") ) {
            //充值金额
            $money = $request->getParameter("Amount",0);
            
            $bank_type = $request->getParameter("Bank");
            //判断是否绑定过银行卡
            $user_bank= Doctrine::getTable('UserBankCards')->findOneByUserId($user_id);
            if(empty($user_bank)){
                $this->getUser()->setFlash('error', '请先绑定银行卡');
                $this->redirect('account/recharge');
            }
            
            //判断金额是否大于10
//            if($money<10){
//                $this->getUser()->setFlash('error', '充值金额必须大于10元');
//                $this->redirect('account/recharge');
//            }
            
            //判断是否选择银行
            if(empty($bank_type)){
                $this->getUser()->setFlash('error', '请选择银行');
                $this->redirect('account/recharge');
            }
            
            //添加充值记录
            $inpour_onlines=new InpourOnlines();
            $serial_id='vm'.date("Ymdhis").$user_id.rand(1000,9999);
            $inpour_onlines->setUserId($user_id)
                    ->setSerialId($serial_id)//流水号
                    ->setStatus(0)//充值状态,0 :未成功  1:成功
                    ->setTotalFee($money)//充值金额
                    ->setReturnTime(date("Y-m-d H:i:s"))
                    ->save();
            
            $this->redirect('account/pay?order='.$serial_id.'&money='.$money.'&bank_code='.$bank_type);
        }
     }
     
     
      public function executePay(sfWebRequest $request){
         
            $yeepayCommon=new yeepayCommon();
            $this->p0_Cmd=$yeepayCommon->p0_Cmd;
            $this->p1_MerId=$yeepayCommon->p1_MerId;
            $this->p9_SAF =$yeepayCommon->p9_SAF;
            //商户订单号
            $this->p2_Order = $request->getParameter('order');
           
            //支付金额,必填.单位:元，精确到分.
            $this->p3_Amt	=  $request->getParameter('money');
           
            //商品名称 用于支付时显示在易宝支付网关左侧的订单产品信息.
            $this->p5_Pid	= "productname";
            
            //商品种类
            $this->p6_Pcat = "producttype";
          
            //商品描述
            $this->p7_Pdesc = "productdesc";
            $this->p8_Url ='http://192.168.1.176/vmdai/web/index.php/account/callback';
            //$this->p8_Url ='http://203.195.130.112/web/index.php/account/callback';
            //商户扩展信息 商户可以任意填写1K 的字符串,支付成功时将原样返回.												
            $this->pa_MP = md5($request->getParameter('order'));
            
            //支付通道编码 默认为""，到易宝支付网关.若不需显示易宝支付的页面，直接跳转到各银行、神州行支付、骏网一卡通等支付页面，该字段可依照附录:银行列表设置参数值.			
            $this->pd_FrpId = $request->getParameter('bank_code');
            
            //应答机制 #默认为"1": 需要应答机制;
            $this->pr_NeedResponse = "1";
            //调用签名函数生成签名串
            
            $this->hmac = $yeepayCommon->getReqHmacString($this->p2_Order,$this->p3_Amt,"CNY",$this->p5_Pid,$this->p6_Pcat,$this->p7_Pdesc,$this->p8_Url,$this->pa_MP,$this->pd_FrpId,$this->pr_NeedResponse);  
  
            $this->reqURL_onLine = "https://www.yeepay.com/app-merchant-proxy/node";
            
             
     }
     
     
     public function executeCallback(sfWebRequest $request){
      
          #	只有支付成功时易宝支付才会通知商户.
            ##支付成功回调有两次，都会通知到在线支付请求参数中的p8_Url上：浏览器重定向;服务器点对点通讯.

            #	解析返回参数.
            $yeepayCommon=new yeepayCommon();
            
            $return = $yeepayCommon->getCallBackValue($r0_Cmd,$r1_Code,$r2_TrxId,$r3_Amt,$r4_Cur,$r5_Pid,$r6_Order,$r7_Uid,$r8_MP,$r9_BType,$hmac);

            #	判断返回签名是否正确（True/False）
            $bRet = $yeepayCommon->CheckHmac($r0_Cmd,$r1_Code,$r2_TrxId,$r3_Amt,$r4_Cur,$r5_Pid,$r6_Order,$r7_Uid,$r8_MP,$r9_BType,$hmac);
            #	以上代码和变量不需要修改.

            #	校验码正确.
            if($bRet){
                    if($r1_Code=="1"){

                    
                        #需要比较返回的金额与商家数据库中订单的金额是否相等，只有相等的情况下才认为是交易成功.
                        
                        $inpour_onlines= Doctrine::getTable('InpourOnlines')->createQuery()
                                                        ->where('serial_id = ?',$r6_Order)
                                                        ->execute();
                        
                        if($r3_Amt==$inpour_onlines[0]->getTotalFee()){
                            $r3_Amt=1000;
                            //修改充值记录
                                $total_pay= bcsub($r3_Amt,$r3_Amt*0.003,sfConfig::get('app_value_bit'));
                                $inpour_onlines[0]->setDealingId($r2_TrxId)
                                        ->setStatus(1)
                                        ->setDealingTime(date("Y-m-d H:i:s"))
                                        ->setTotalPay($total_pay)
                                        ->save();
                                
                                
                                
                                //增加用户余额变更记录
                                $account_money_record = new AccountMoneyChangeRecord();
                                $account_money_record->setUserId($inpour_onlines[0]->getUserId())
                                                    ->setActionType(AccountMoneyChangeRecord::RECHARGE)
                                                    ->setCurrentMoney($total_pay)
                                                    ->save();
                                
                                
                                //获取用户账户
                                $account =  Doctrine::getTable('UserAccount')->findOneByUserId($inpour_onlines[0]->getUserId());
                                
                                //添加充值账户明细记录
                                $accountdetails = new AccountDetails();
                                $accountdetails->setUserId($inpour_onlines[0]->getUserId())
                                        ->setEvent(0)
                                        ->setMoney($r3_Amt)
                                        ->setEventRelationId($inpour_onlines[0]->getId())
                                        ->setBalance(bcadd($account->getBalance(),$r3_Amt*0.003,sfConfig::get('app_value_bit')))
                                        ->setRemainingMoney(bcadd($account->getRemainingMoney(),$r3_Amt*0.003,sfConfig::get('app_value_bit')))
                                        ->setDescription("易宝支付即时到帐充值￥".number_format($r3_Amt,2)."，Online：{$inpour_onlines[0]->getId()}")
                                        ->save();
                               
                                //添加手续费扣除记录
                                $recharge_fee_record = new RechargeFeeRecord();
                                $recharge_fee_record->setUserId($inpour_onlines[0]->getUserId())
                                                ->setPreMoney($r3_Amt)
                                                ->setCurrentMoney($r3_Amt*0.003)
                                                ->setNextMoney($total_pay)
                                                ->setTypes(1)
                                               
                                                ->save();
                                
                                
                                //添加充值手续费明细记录
                                $accountdetails = new AccountDetails();
                                $accountdetails->setUserId($inpour_onlines[0]->getUserId())
                                        ->setEvent(7)
                                        ->setMoney($r3_Amt*0.003)
                                        ->setEventRelationId($recharge_fee_record->getId())
                                        ->setBalance($account->getBalance())
                                        ->setRemainingMoney($account->getRemainingMoney())
                                         ->setDescription("扣除易宝支付即时到帐充值手续费￥".number_format($r3_Amt*0.003,2)."，OnlineId：".$recharge_fee_record->getId())
                                        ->save();
                               
                                
                                
                            if($r9_BType=="1"){
                                
                                    echo "交易成功";
                                    echo  "<br />在线支付页面返回";exit;
                            }elseif($r9_BType=="2"){
                                    echo "success";
                                   	 
                            }
                        }else{
                            echo "交易信息不符！";exit;
                        }
                      	  	

                            
                    }

            }else{
                    echo "交易信息被篡改！";exit;
            }
   
     }
      

      
      /**
       * 我的借款
       * @param sfWebRequest $request
       */
      public function executeMyloan(sfWebRequest $request){ 
        $this->getResponse()->setTitle("我的借款");
         $user_id = $this->getUser()->getAttribute("user_id");
         $loan_list = Doctrine::getTable('Loan')->createQuery()->where('user_id = ?',$user_id)->andWhere("status = ?",4)->orderBy('created_at desc');

         $this->pager = new sfDoctrinePager("Loan", 10);
         $this->pager->setQuery($loan_list);
         $page = $request->getParameter('page',1);
         $this->pager->setPage($request->getParameter('page',1));
         $this->pager->init();
      }
      /**
       * 我的借款（已经发布）
       */
      public function executePublished(sfWebRequest $request){
         $this->getResponse()->setTitle("我的借款");
           $this->type_list = Doctrine::getTable('LoanListType')->findAll()->toKeyValueArray('id', 'name');//列表类型
          
          $user_id = $this->getUser()->getAttribute("user_id");
          $loan_list = Doctrine::getTable('Loan')->createQuery()->where('user_id = ?',$user_id)->andWhere("status != ?",4)->orderBy('created_at desc');
          
          $this->pager = new sfDoctrinePager("Loan", 10);
          $this->pager->setQuery($loan_list);
          $page = $request->getParameter('page',1);
          $this->pager->setPage($request->getParameter('page',1));
          $this->pager->init();
      }
      

      public function executeRepayment(sfWebRequest $request) {
          $user_id = $this->getUser()->getAttribute("user_id");
          $loan_id = (int)$request->getParameter("id", 0);

          if($loan_id){
              $this->list = Doctrine::getTable('LoanInstallment')->createQuery()->where('loan_id = ?',$loan_id)->execute();
              $this->loan = Doctrine::getTable('Loan')->findOneById($loan_id);
              if(empty($this->loan)){
                  $this->forward404();
              }
              if($this->loan->getUserId() != $user_id) {
                  $this->getUser()->setFlash('error', '不是当前用户，不能对该项目进行操作');
                  $this->redirect("account/myloan");
              }
          }
          
          $this->user_account = Doctrine::getTable('UserAccount')->findOneByUserId($user_id);
          
         $this->current_money = 0;
         $loanInstallment = Doctrine::getTable('LoanInstallment')->createQuery()->where('loan_id = ?',$loan_id)->andWhere('status = ?',0)->orderBy('id ASC')->fetchOne();
         if($loanInstallment){
            $current_principal_money = $this->loan->getMoney();
            $begin_time = $loanInstallment->getCurrentStartTime();
            $rate = bcdiv($this->loan->getMoneyRate(),100,sfConfig::get('app_value_bit'));
            $term_num = (strtotime(date("Y-m-d")) - strtotime(date("Y-m-d",strtotime($begin_time))))/86400;
            $money_rate = bcmul($current_principal_money, $rate, sfConfig::get('app_value_bit'));  //投资额*利率
            $day_rate = bcdiv($money_rate, 360, sfConfig::get('app_value_bit'));//计算每天利息，除以360
            $current_interest_money = bcmul($day_rate,$term_num,sfConfig::get('app_value_bit'));//天标计算总共利息
            if($current_interest_money < 0) $current_interest_money = 0;
            $this->current_money = bcadd($current_interest_money,$current_principal_money,sfConfig::get('app_value_bit'));
         }
          
      }
      /**
       * 还款动作
       * @param sfWebRequest $request
       */
      public function executeRepay(sfWebRequest $request) {
          $user_id = $this->getUser()->getAttribute("user_id");
          $loan_id = (int)$request->getParameter("loan_id", 0);
          $type = (int)$request->getParameter("RepaymentType", 0);//还款类型：当期，所有
          $count = Doctrine_Manager::connection()->execute("SELECT count(id) FROM loan_installment where loan_id = $loan_id AND status = 0")->fetchColumn(); if($count == 1) $type = 1;
          
           //用户账户信息
          $user_account = Doctrine::getTable('UserAccount')->findOneByUserId($user_id);
          
          //当前期
          if($type == 1){
              $time_status = false;
              //获取最近一期分期
              $loanInstallment = Doctrine::getTable('LoanInstallment')->createQuery()->where('loan_id = ?',$loan_id)->andWhere('status = ?',0)->limit(1)->orderBy('periodization')->fetchOne();
              //还款记录
              if($loanInstallment){
                  //本期所还金额
                  $current_money =  $loanInstallment->getCurrentMoney();
                  //本金
                  $current_principal_money = $loanInstallment->getCurrentPrincipalMoney();
                  //利息
                  $current_interest_money = $loanInstallment->getCurrentInterestMoney();
                  $is_advance = 0;
              }
          }else{
              //最近一期未还的分期
              $loanInstallment = Doctrine::getTable('LoanInstallment')->createQuery()->where('loan_id = ?',$loan_id)->andWhere('status = ?',0)->orderBy('id ASC')->fetchOne();
              $loan_model = Doctrine::getTable('Loan')->findOneById($loan_id);
              $current_principal_money = $loan_model->getMoney();

              $begin_time = $loanInstallment->getCurrentStartTime();
              $rate = bcdiv($loan_model->getMoneyRate(),100,sfConfig::get('app_value_bit'));
              $term_num = (strtotime(date("Y-m-d")) - strtotime(date("Y-m-d",strtotime($begin_time))))/86400;

              $money_rate = bcmul($current_principal_money, $rate, sfConfig::get('app_value_bit'));  //投资额*利率
              $day_rate = bcdiv($money_rate, 360, sfConfig::get('app_value_bit'));//计算每天利息，除以360
              $current_interest_money = bcmul($day_rate,$term_num,sfConfig::get('app_value_bit'));//天标计算总共利息
              if($current_interest_money < 0) $current_interest_money = 0;
              $current_money = bcadd($current_interest_money,$current_principal_money,sfConfig::get('app_value_bit'));
              $is_advance = 1;
          }
          
          
            if($user_account->getRemainingMoney() < $current_money){
                $this->getUser()->setFlash('error', '您的可用余额不足');
                $this->redirect('account/repayment?id='.$loan_id);
            }
          
         //期数
        $periodization = $loanInstallment->getPeriodization();
        //分期还款id
        $loaninstallment_id = $loanInstallment->getId(); 
        //保存记录
        $RepaymentRecords = new RepaymentRecords();
        $result = $RepaymentRecords->setUserId($user_id)
                ->setCurrentMoney($current_money)//本息 
                ->setCurrentInterestMoney($current_interest_money)//利息
                ->setCurrentPrincipalMoney($current_principal_money)//本金
                ->setPeriodization($periodization)
                ->setLoanId($loan_id)
                ->setLoaninstallmentId($loaninstallment_id)
                ->setIsAdvance($is_advance)
                ->save();
        
        $this->getUser()->setFlash('good', '');
        $this->redirect("account/repayment?id=".$loan_id);
      }
      
      
      
      /**
       * 绑定银行卡
       * @param sfWebRequest $request
       */
      public function executeBindcard(sfWebRequest $request) {
        //用户ID
         $user_id = $this->getUser()->getAttribute("user_id");
        //银行列表
         $this->bank_list = Doctrine::getTable('BankTypes')->createQuery()
                                                        ->where('is_display = ?',1)
                                                        ->execute();
         
         $this->uname=Doctrine::getTable('UserAttr')->createQuery()
                                                        ->where('user_id = ?',$user_id)
                                                        ->andWhere('attr_name = ?','name')
                                                        ->execute();
          if( $request->isMethod("POST") ) {
             
            #真实名称
            $user_name = $request->getParameter("username");
            #真实名称
            $real_name = $request->getParameter("RealName");
            #银行卡号
            $bank_num = $request->getParameter("BankNumber");
            $re_bank_num = $request->getParameter("ReBankNumber");
            #银行类型ID
            $bank_id = $request->getParameter("BankTypeId");
            #城市
            $city = $request->getParameter("city");
            #开户行名称
            $bank_name = $request->getParameter("BankName"); 
            #支行名称
            $branch_name = $request->getParameter("BranchName");
            
            
            
            //添加银行卡
            $bank_cards=Doctrine::getTable('UserBankCards')->findBy('user_id', $user_id);
            foreach ($bank_cards as $key){
              $key->setStatus(0)->save();
            }
            $user_bank_cards = new UserBankCards();
            $user_bank_cards->setUserId($user_id)
                     ->setCity($city)
                    ->setBankId($bank_id)
                    ->setBankName($bank_name)
                    ->setBranchName($branch_name)
                    ->setBankNum($bank_num)
                    ->setRealName($real_name)
                    ->setStatus(1)
                    ->save();
           echo "<script/>window.parent.location.reload() </script>";
           
           
            
                    
          }
          
      }
      
      
      /**
       * 提现
       * @param sfWebRequest $request
       */
      public function executeWithdrawcash(sfWebRequest $request) {
        $this->getResponse()->setTitle("账户提现");
          //用户ID
         $user_id = $this->getUser()->getAttribute("user_id");
         //获取用户绑定的银行卡
         $this->user_cards = Doctrine::getTable('UserBankCards')->createQuery()
                                                        ->where('user_id = ?',$user_id)
                                                        ->andWhere('status = ?','1')
                                                        ->execute();
         //尾号
         $this->last_num=substr($this->user_cards[0]->getBankNum(),-4);
         //银行卡信息
         $this->cards=Doctrine::getTable('BankTypes')->find($this->user_cards[0]->getBankId());
         
         $this->user = Doctrine::getTable('UserAccount')->findOneByUserId($user_id);
         
         $this->drawlist= Doctrine::getTable('UserAccountCashRecord')->createQuery() ->where('user_id = ?',$user_id)->orderBy('created_at desc')->execute();
         if( $request->isMethod("POST") ) {
             
             
            #本次提现申请金额
            $current_money = $request->getParameter("current_money");
            
            #提现手续费
            $fee = $request->getParameter("fee");
            
            #实际提现金额
            $next_money = bcsub((int)$current_money,(int)$fee,sfConfig::get('app_value_bit'));
            
            #用户绑定的银行卡记录ID
            $user_bank_id = $request->getParameter("user_bank_id");
            
            $serial_id='vmdraw'.date("Ymdhis").$user_id.rand(1000,9999);
            
            //添加用户提现记录
            $user_cash_record = new UserAccountCashRecord();
            $user_cash_record->setUserId($user_id)
                    ->setCurrentMoney($current_money)
                    ->setNextMoney($next_money)
                    ->setFee($fee)
                    ->setStatus(0)//提现状态,0 :申请中  1:成功 2：失败 3：撤回
                    ->setUserBankId($user_bank_id)
                    ->setSerialId($serial_id)
                    ->setIp($request->getRemoteAddress())
                    ->save();
            
            
                    
            //增加用户余额变更记录
            $account_money_record = new AccountMoneyChangeRecord();
            $account_money_record->setUserId($user_id)
                               ->setActionType(AccountMoneyChangeRecord::TIXIAN)
                               ->setCurrentMoney($current_money)
                               ->save();
                               
            //添加手续费扣除记录
            $recharge_fee_record = new RechargeFeeRecord();
            $recharge_fee_record->setUserId($user_id)
                            ->setPreMoney($current_money)
                            ->setCurrentMoney($fee)
                            ->setNextMoney($next_money)
                            ->setTypes(2)
                            ->save();
            
            //修改用户绑定卡的提现总金额
            $draw_money=bcadd($this->user_cards[0]->getDrawMoney(), $current_money, sfConfig::get('app_value_bit'));
            $fee_money=bcadd($this->user_cards[0]->getFeeMoney(), $fee, sfConfig::get('app_value_bit'));
            $this->user_cards[0]->setDrawMoney($draw_money)
                    ->setFeeMoney($fee_money)
                    ->save();
            
            //添加提现手续费明细记录
            //获取用户账户
            $account =  Doctrine::getTable('UserAccount')->findOneByUserId($user_id);
            $accountdetails = new AccountDetails();
            $accountdetails->setUserId($user_id)
                           ->setEvent(1)
                           ->setMoney($next_money)
                           ->setEventRelationId($user_cash_record->getId())
                           ->setBalance($account->getBalance())
                           ->setRemainingMoney($account->getRemainingMoney())
                          ->setDescription("取现￥".  number_format($current_money,2))
                           ->save();
            $this->redirect("account/withdrawcash");
          }
      }

      public function executeBacklend(sfWebRequest $request) {
         $this->getResponse()->setTitle("投标概况");
          //用户ID
            $user_id = $this->getUser()->getAttribute("user_id");
            $result = Doctrine::getTable("InvestInstallment")->createQuery()->select('loan_id')->where("status = ?",4)->fetchArray();
            $loan_array = array();
            if(!empty($result)){
                foreach ($result as $one_result){
                    $loan_array[] = $one_result['loan_id'];
                }
            }
            $query = Doctrine::getTable('InvestInstallment')->createQuery()->select("*,SUM(current_money) as current_money,SUM(current_principal_money) AS current_principal_money")->where("user_id = ?",$user_id)->andWhere("status = ?",0);
            if(!empty($loan_array)){
                $query->whereNotIn("loan_id", $loan_array);
            }
            $query->groupBy('loan_id');
            $page = $request->getParameter('page',1);
            $this->pager = new sfDoctrinePager('InvestInstallment',10);
            $this->pager->setQuery($query);
            $this->pager->setPage($page);
            $this->pager->init();
            
      }
      
      //已回款
      public function executeReturnedend(sfWebRequest $request){
            $user_id = $this->getUser()->getAttribute("user_id");
            $this->user_id=$user_id;
           $result = Doctrine::getTable("Loan")->createQuery()->select('id')->where("status = ?",5)->fetchArray();
            $loan_array = array();
            if(!empty($result)){
                foreach ($result as $one_result){
                    $loan_array[] = $one_result['id'];
                }
            }
            $query = Doctrine::getTable('InvestInstallment')->createQuery()->select("*,SUM(current_money) as current_money,SUM(current_principal_money) AS current_principal_money")->where("user_id = ?",$user_id)->andWhereIn("loan_id", $loan_array)->groupBy("loan_id");
           
            $page = $request->getParameter('page',1);
            $this->pager = new sfDoctrinePager('InvestInstallment',10);
            $this->pager->setQuery($query);
            $this->pager->setPage($page);
            $this->pager->init();
            
            //已回款
            $sql = "SELECT SUM(current_money) as current_money FROM invest_installment as a LEFT JOIN loan as l ON a.loan_id=l.id  WHERE a.user_id = $user_id AND l.`status` =5 ;";
         
            $this->already_repaymenting = Doctrine_Manager::connection()->execute("$sql")->fetch();

        
      }
      
      public function executeInbids(sfWebRequest $request){
          $user_id = $this->getUser()->getAttribute("user_id");
          $this->user_id=$user_id;
          $query = Doctrine::getTable('LoanRecord')->createQuery()->select("*,SUM(loan_money) as loan_moneys")->where("user_id = ?",$user_id)->andWhere("status = ?",0)->groupBy('loan_id'); 
          
          $page = $request->getParameter('page',1);
          $this->pager = new sfDoctrinePager('LoanRecord',10);
          $this->pager->setQuery($query);
          $this->pager->setPage($page);
          $this->pager->init();
          
         $this->loaning = Doctrine::getTable('LoanRecord')->createQuery()->select("SUM(loan_money) as loan_money")->where("user_id = ?",$user_id)->andWhere("status = ?",0)->fetchOne();
      }
      
      //投标失败(流标)
      public function executeBidfail(sfWebRequest $request) {
          $user_id = $this->getUser()->getAttribute("user_id");
          $this->user_id = $user_id;
          $query = Doctrine::getTable('LoanRecord')->createQuery()->select("*,SUM(loan_money) as loan_money")->where("user_id = ?",$user_id)->andWhere("status = ?",2)->groupBy('loan_id'); 
          $page = $request->getParameter('page',1);
          $this->pager = new sfDoctrinePager('LoanRecord',10);
          $this->pager->setQuery($query);
          $this->pager->setPage($page);
          $this->pager->init();
          
         $this->loaning = Doctrine::getTable('LoanRecord')->createQuery()->select("SUM(loan_money) as loan_money")->where("user_id = ?",$user_id)->andWhere("status = ?",0)->fetchOne();
      }
      
      
      //交易明细(需要交易明细表)
      public function executeActivity(sfWebRequest $request){
          $user_id = $this->getUser()->getAttribute("user_id");
          $this->user_account = Doctrine::getTable('UserAccount')->findOneByUserId($user_id);
          //已取现总额
          $this->user_account_cash = Doctrine::getTable('UserAccountCashRecord')->createQuery()->select("SUM(next_money) as next_money")->where("status = ?",1)->andWhere("user_id = ?",$user_id)->groupBy("user_id")->fetchOne();
          
      }

      
      /**
       * 待回款
       * @param sfWebRequest $request
       */
      public function executeAwait(sfWebRequest $request) {
        $this->getResponse()->setTitle("待回款项");
          $user_id = $this->getUser()->getAttribute("user_id");
          $this->startDate = $request->getParameter("startDate","");
          $this->endDate = $request->getParameter("endDate","");

          $start_month = date("Y-m")."-01 00::00:00";
          $days = date('t');
          $end_month = date("Y-m")."-"."$days 00::00:00";
          $sql = "SELECT SUM(current_money) as current_money
                    FROM `invest_installment` WHERE user_id = $user_id AND status = 0 AND current_end_time Between '$start_month' AND '$end_month'
                        AND loan_id NOT IN (SELECT `loan_id` FROM `invest_installment` WHERE `status` = 4)";
          $this->td_month_repaymenting = Doctrine_Manager::connection()->execute("$sql")->fetch();
          $next_start_month = date('Y-m',strtotime('+1 month'))."-01 00::00:00";
          $next_days = date('t',strtotime('+1 month'));
          $next_end_month = date("Y-m",strtotime('+1 month'))."-"."$next_days 00::00:00";
          $sql = "SELECT SUM(current_money) as current_money
                    FROM `invest_installment` WHERE user_id = $user_id AND status = 0 AND current_end_time Between '$next_start_month' AND '$next_end_month'
                        AND loan_id NOT IN (SELECT `loan_id` FROM `invest_installment` WHERE `status` = 4)";
          $this->next_month_repaymenting = Doctrine_Manager::connection()->execute("$sql")->fetch();

          $td_start_year = date("Y")."-01-01 00:00:00";
          $td_end_year = date("Y")."-12-31 00:00:00";
          $sql = "SELECT COUNT(id) as count,SUM(current_money) as current_money
                    FROM `invest_installment` WHERE user_id = $user_id AND status = 0 AND current_end_time Between '$td_start_year' AND '$td_end_year'
                        AND loan_id NOT IN (SELECT `loan_id` FROM `invest_installment` WHERE `status` = 4)";
         $this->td_year_repaymenting = Doctrine_Manager::connection()->execute("$sql")->fetch();

         $sql = "SELECT COUNT(id) as count,SUM(current_money) as current_money
                    FROM `invest_installment` WHERE user_id = $user_id AND status = 0 AND loan_id NOT IN (SELECT `loan_id` FROM `invest_installment` WHERE `status` = 4)";
         $this->all = Doctrine_Manager::connection()->execute("$sql")->fetch();

        $result = Doctrine::getTable("InvestInstallment")->createQuery()->select('loan_id')->where("status = ?",4)->fetchArray();
        $loan_array = array();
        if(!empty($result)){
            foreach ($result as $one_result){
                $loan_array[] = $one_result['loan_id'];
            }
        }

        $query = Doctrine::getTable('InvestInstallment')->createQuery()->where("status = ?",0)->andWhere("user_id = ?",$user_id);
        if(!empty($loan_array)){
            $query->whereNotIn("loan_id", $loan_array);
        }
        if(!empty($this->startDate) && !empty($this->endDate)){
            $query->andWhere("current_end_time >= ?",$this->startDate."00:00:00");
            $query->andWhere("current_end_time <= ?",$this->endDate."00:00:00");
        }       
        $this->pager = new sfDoctrinePager('InvestInstallment',10);
        $this->pager->setQuery($query);
        $page = $request->getParameter('page',1);
        $this->pager->setPage($page);
        $this->pager->init();
        $a = clone $query;
        $this->current_money = $a->select("SUM(current_money) as current_money")->fetchOne();

        
      }
      
      public function executeBorrow(sfWebRequest $request) {
        $this->getResponse()->setTitle("借款统计");
         $user_id = $this->getUser()->getAttribute("user_id");
         $this->user_account =  Doctrine::getTable('UserAccount')->findOneByUserId($user_id);
         $sql = "SELECT SUM(current_interest_money) as current_interest_money,
             SUM(current_money) as current_money,
             SUM(current_principal_money) as current_principal_money
         FROM `loan_installment` WHERE loan_user_id = $user_id AND status = 0
         AND loan_id NOT IN (SELECT `loan_id` FROM `loan_installment` WHERE `status` = 4)";
         $this->wait_pay = Doctrine_Manager::connection()->execute("$sql")->fetch();
         $sql = "SELECT SUM(current_principal_money) as current_principal_money,SUM(current_interest_money) as current_interest_money
            FROM `loan_installment` WHERE loan_user_id = $user_id AND  status <> 2";
         $this->all_interest = Doctrine_Manager::connection()->execute("$sql")->fetch();
          $sql = "SELECT SUM(service_fee) as service_fee_money
            FROM `loan` WHERE user_id = $user_id AND status in (4,5)";
          
         $this->all_service = Doctrine_Manager::connection()->execute("$sql")->fetch();
        $sql = "SELECT SUM(current_interest_money) as current_interest_money,
            SUM(current_money) as current_money,
            SUM(current_principal_money) as current_principal_money
        FROM `loan_installment` WHERE loan_user_id = $user_id AND (`status` = 1 OR `status` = 3)
        or loan_id IN (SELECT `loan_id` FROM `loan_installment` WHERE `status` = 4 AND loan_user_id = $user_id)";
        
        $this->wait_lasted_pay = Doctrine_Manager::connection()->execute("$sql")->fetch();
        
        
        
      }

       public function executeLend(sfWebRequest $request) {
          $this->getResponse()->setTitle("理财统计");
          $user_id = $this->getUser()->getAttribute("user_id");
          $this->user_account =  Doctrine::getTable('UserAccount')->findOneByUserId($user_id);
          $this->result_loan_money = array(0,0,0,0,0,0,0);
          $result = Doctrine::getTable("LoanRecord")->createQuery()->select("SUM(loan_money) AS loan_money,type_id")->WHERE("user_id = ?",$user_id)->andWhere("status=?",1)->groupBy("type_id")->execute();
          if(!empty($result)){
              foreach ($result as $one){
                  $type_id = $one->getTypeId();
                  $this->result_loan_money[$type_id] = $one->getLoanMoney();
              }
          }
            $sql = "SELECT SUM(current_principal_money) as current_principal_money,SUM(current_interest_money) as current_interest_money FROM `invest_installment` WHERE user_id = $user_id AND status = 0 AND loan_id NOT IN (SELECT `loan_id` FROM `invest_installment` WHERE `status` = 4)";$wait_result = Doctrine_Manager::connection()->execute("$sql")->fetch();
          $sql = "SELECT SUM(current_principal_money) as current_principal_money,SUM(current_interest_money) as current_interest_money FROM `invest_installment` WHERE user_id = $user_id AND status <> 2";
          $this->sum_result = Doctrine_Manager::connection()->execute("$sql")->fetch();
          $this->current_principal_money=bcsub($this->sum_result['current_interest_money'],$wait_result['current_interest_money'],sfConfig::get('app_value_bit'));
          $this->next_money = Doctrine::getTable("RechargeFeeRecord")->createQuery("SUM(next_money) as next_money")->where("user_id = ?",$user_id)->andWhere("types = ?",2)->fetchOne();
          
      }
      
      /**
       * ajax请求加载页面
       */
      public function executeDetailed(sfWebRequest $request){
        
      }
      
     
     

}
